/**
 * 
 */
package com.javatom.notes.authority.sms;

import com.javatom.notes.authority.service.Outh2UserDetailsService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;

/**
 * createUser: 曾维录
 * FileName: SmsCodeAuthenticationFilter
 * Author: 14562
 * Date:  2019/12/23 16:10
 * Description: 短信登录验证逻辑
 */
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

	private Outh2UserDetailsService outh2UserDetailsService;



	/*
	 * 
	 * @see org.springframework.security.authentication.AuthenticationProvider#
	 * authenticate(org.springframework.security.core.Authentication)
	 */
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {

		SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
		//验证短信验证码
        String smsCode = authenticationToken.getCredentials() == null ? "" : authenticationToken.getCredentials().toString();

        if (StringUtils.isEmpty(smsCode)) {
            throw new InternalAuthenticationServiceException("无法获取验证码");
        }
        String mobile = authenticationToken.getPrincipal() == null ? "" : authenticationToken.getPrincipal().toString();
        if (StringUtils.isEmpty(mobile)) {
            throw new InternalAuthenticationServiceException("无法获取手机号");
        }
        if(!checkSmsCode(smsCode)) {
            throw new InternalAuthenticationServiceException("验证码错误");
        }
		
		UserDetails user = outh2UserDetailsService.loadUserByMobile(mobile);

		if (user == null) {
			throw new InternalAuthenticationServiceException("无法获取用户信息");
		}
		
		SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user, user.getAuthorities(),mobile,smsCode);
		
		authenticationResult.setDetails(authenticationToken.getDetails());

		return authenticationResult;
	}

    private boolean checkSmsCode(String smsCode) {
	    return true;
    }

    /*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.authentication.AuthenticationProvider#
	 * supports(java.lang.Class)
	 */
	@Override
	public boolean supports(Class<?> authentication) {
		return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
	}

    public Outh2UserDetailsService getOuth2UserDetailsService() {
        return outh2UserDetailsService;
    }

    public void setOuth2UserDetailsService(Outh2UserDetailsService outh2UserDetailsService) {
        this.outh2UserDetailsService = outh2UserDetailsService;
    }
}
